package com.gzsxy.syn;

//不安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "小张").start();
        new Thread(buyTicket, "小蔡").start();
        new Thread(buyTicket, "小郑").start();
    }
}


class BuyTicket implements Runnable {

    //票
    int ticketNums = 10;
    boolean flag = true; //外部停止方式


    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    //synchronized保证同步，统一时间只有一个线程进入该方法
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }

        //模拟延时

        Thread.sleep(100);

        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}
